package com.itheima.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.R;
import com.itheima.service.ShoppingCartService;
import com.itheima.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart ){

        //1. 补充数据
        shoppingCart.setUserId(BaseContext.getCurrentId());


        //2. 添加购物车

        //2.0 得先查询购物车数据：
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId , BaseContext.getCurrentId());//设置用户的id
        //设置菜品id或者套餐id
        if(shoppingCart.getDishId() != null ){
            lqw.eq(ShoppingCart::getDishId , shoppingCart.getDishId());
        }else{
            lqw.eq(ShoppingCart::getSetmealId , shoppingCart.getSetmealId());
        }

        //查询购物车数据
        ShoppingCart cartInDB = shoppingCartService.getOne(lqw);

        if(cartInDB != null){
            //2.1 如果已经有了这件菜品|套餐，那么就是修改数量即可
            cartInDB.setNumber(cartInDB.getNumber() + 1);
            //2.2 更新数据
            shoppingCartService.updateById(cartInDB);
        }else{
            //2.2 如果没有这件菜品|套餐，那么就是添加操作
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            cartInDB = shoppingCart;
        }
        return R.success(cartInDB);
    }

    /**
     * 查看购物车数据
     * @return
     */
    @GetMapping("/list")
    public R list(){

        //1. 按照用户的id来查询购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId , BaseContext.getCurrentId());

        //2. 执行查询
        List<ShoppingCart> cartList = shoppingCartService.list(lqw);

        return R.success(cartList);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){
        //1. 按照用户的id来清空购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId , BaseContext.getCurrentId());

        //2. 直接做删除操作
        boolean result = shoppingCartService.remove(lqw);
        if(result){
            return R.success("清空购物车成功！");
        }
        return R.error("清空购物车失败！");

    }
}
